import {debounce,throttle} from '/util/debounce';

Page({
  data: {
    value: '',  //搜索框
    focus:false,
    history: my.getStorageSync({ key: 'searchHistory' }).data || [],
    drawList:[],  //画稿列表
    drawSuggestions: []  //画稿条件查询过滤列表
  },
  onLoad(param) {
    
    if(param.type == "search"){
      this.setData({
        focus:true
      })
    }
  },
  onShow() {

    let token = my.getStorageSync({ key: 'token' }).data;
    if(token == null){
      my.confirm({
      title: '温馨提示',
      content: '当前还未登录：是否需要登录？',
      confirmButtonText: '马上登录',
      cancelButtonText: '暂不需要',
      success: (result) => {
        if(result.confirm){
            //登录
            my.navigateTo({
             url: '/pages/common/login/login'
            })
        }else{
          //暂不登录
            my.switchTab({
             url: '/pages/index/index'
            })
        }
        },
      });
      return false;
    }
    
    this.setData({
      value:''
    })
    this.getDrawList(token);
    this.setData({
      history: my.getStorageSync({ key: 'searchHistory' }).data,
    });
    // this.onInput = debounce(this.onInput.bind(this), 400);
    my.setNavigationBar({
      borderBottomColor: '#fff',
    });
  
  },
  getDrawList(token){
      let that = this;
      my.showLoading({
        content: '加载中...'
      });
        //请求数据
      my.request({
      url: 'https://tiyi.site/seaHorse/app/drawAuth/drawList',
      method: 'POST',
      headers: 
      {
       'content-type': 'application/json',
       'token':token
      },
      data: {},
      dataType: 'json',
      success: function(res) {
        if(res.data.code == 0){
          that.setData({
            drawList:res.data.list,
            drawSuggestions:res.data.list
          })
        }else if(res.data.code == 401){
            //去登录
            my.navigateTo({
              url: '/pages/common/login/login'
            }) 
        }
      },
      fail: function(res) {
        my.alert({content: res});
      },
      complete: function(res) {
        my.hideLoading();
      }
      });
  },
  clear() {
    my.confirm({
      content: '确定删除相关历史？',
      success: (res) => {
        if (res.confirm) {
          my.clearStorage();
          this.setData({
            history: [],
          });
        }
      },
    })
  },
  //输入值
  onInput(keyword) {

   
  },
  //提交
  onSubmit(keyword){

    if(keyword){
      my.showLoading({
          content: '加载中...'
        });
      this.setData({
        value: keyword,
      });
      const regExp = /[A-Za-z]/;
      if (keyword === '' || (regExp.test(keyword) && keyword.length === 1)) {
        this.setData({
          drawSuggestions: [],
        });
        return;
      }

      const drawSuggestions = [];
      for (let i = 0; i < this.data.drawList.length; i++) {
        if (this.data.drawList[i].drawName.toLocaleLowerCase().indexOf(keyword.toLocaleLowerCase()) != -1) {
          drawSuggestions.push(this.data.drawList[i]);
        }
      }

      this.setData({ drawSuggestions })
      my.hideLoading();
    }
  },
  //清除
  onClear() {
    this.setData({
      value: '',
    });
    //恢复初始值
     const drawSuggestions = [];
     for (let i = 0; i < this.data.drawList.length; i++) {
      drawSuggestions.push(this.data.drawList[i]);
    }

    this.setData({ drawSuggestions });

  },
  //取消
  onCancel() {
    this.setData({
      value: '',
    });
    //恢复初始值
    const drawSuggestions = [];
    for (let i = 0; i < this.data.drawList.length; i++) {
      drawSuggestions.push(this.data.drawList[i]);
    }
    this.setData({ drawSuggestions });
    my.navigateBack();
  },
  //点击值
  onItemTap({ name }) {
    this.setData({
      value: name,
    });
    // this.onInput(name);
    const drawSuggestions = [];
    for (let i = 0; i < this.data.drawList.length; i++) {
      if (this.data.drawList[i].drawName.toLocaleLowerCase().indexOf(name.toLocaleLowerCase()) != -1) {
        drawSuggestions.push(this.data.drawList[i]);
      }
    }
    this.setData({ drawSuggestions })
  },
  //点击列表
  onItemClick(e) {
   
    const { id,name } = e.target.dataset;
    throttle(this.itemClick(id,name),2000)

  },

  itemClick(id,name){
     this.addToHistory(name);
     this.setData({
      value: '',
    });
    my.navigateTo({
     url: '/pages/detail/detail?drawId='+id
    })
  },
  //添加到历史记录收藏
  addToHistory(keyword) {
    const searchHistory = my.getStorageSync({ key: 'searchHistory' }).data || [];
    let index = -1;

    for (let i = 0; i < searchHistory.length; i++) {
      if (searchHistory[i].name === keyword) {
        index = i;
        break;
      }
    }

    let history = [];

    if (searchHistory.length >= 8) {
      if (index === -1) {
        history = [{ name: keyword }, ...searchHistory.slice(0, 7)];
      } else {
        searchHistory.splice(index, 1).slice(0, 7)
        history = [{ name: keyword }, ...searchHistory];
      }
    } else {
      if (index === -1) {
        history = [{ name: keyword }, ...searchHistory];
      } else {
        searchHistory.splice(index, 1) 
        history = [{ name: keyword }, ...searchHistory];
      }
    }

    my.setStorageSync({
      key: 'searchHistory',
      data: history,
    });

    this.setData({
      history,
    })
  },

  onTabItemTap(item) {
  
  },
  
});